from fastapi import APIRouter, Depends, Query, Body
from src.base.beans import Rest
from src.config.auth import auth_depend
from src.config.db import DbSession
from src.config.log import log_depend
from src.dao.sys_user_dao import get_user_by_id, get_user_list_by_condition, get_user_page_by_condition, insert_user, \
    update_user, delete_users, get_user_role_mapping_list_by_ids
from src.domain.sys_user import SysUser, SysUserReq

router = APIRouter(prefix='/sys/user', dependencies=[Depends(auth_depend), Depends(log_depend)], tags=["用户管理"])


@router.get("/get_by_id/{id}", summary="根据ID获取用户信息", )
async def get_by_id(dbSession: DbSession, id: str):
    sys_user = await get_user_by_id(dbSession, int(id))
    return Rest.ok(sys_user)


@router.get("/list", summary="根据条件查询用户列表", )
async def get_list_by_condition(dbSession: DbSession, search: SysUserReq = Query(default=None)):
    users = await get_user_list_by_condition(dbSession, search)
    user_role = await get_user_role_mapping_list_by_ids(dbSession, [user.user_id for user in users])
    for user in users:
        user.role_ids = [ur.role_id for ur in user_role if ur.user_id == user.user_id] if user_role else []
    return Rest.ok(users)


@router.get("/page", summary="根据条件分页查询用户列表", )
async def get_page_by_condition(dbSession: DbSession, search: SysUserReq = Query(default=None)):
    page_result = await get_user_page_by_condition(dbSession, search)
    user_role = await get_user_role_mapping_list_by_ids(dbSession, [user.user_id for user in page_result.data])
    for user in page_result.data:
        user.role_ids = [ur.role_id for ur in user_role if ur.user_id == user.user_id] if user_role else []
    return Rest.ok(page_result)


@router.post("/create", summary="新增", )
async def create(dbSession: DbSession, entity: SysUserReq = Body()):
    await insert_user(dbSession, entity)
    return Rest.ok()


@router.put("/edit", summary="修改", )
async def edit(dbSession: DbSession, entity: SysUserReq = Body()):
    result = await update_user(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.post("/create_edit", summary="新增或修改", )
async def create_edit(dbSession: DbSession, entity: SysUserReq = Body()):
    result = 1
    if entity.user_id is None:
        await insert_user(dbSession, entity)
    else:
        result = await update_user(dbSession, entity)
    return Rest.ok() if result > 0 else Rest.fail()


@router.delete("/delete", summary="删除", )
async def delete(dbSession: DbSession, ids: list[str] = Query()):
    result = await delete_users(dbSession, [int(id) for id in ids])
    return Rest.ok() if result > 0 else Rest.fail()


# @router.get("/get_all_user_with_dept", summary="获取所有用户信息", )
# async def get_all_user_with_dept(dbSession: DbSession, ):
#     result = await get_user_list_with_dept(dbSession)
#     return Rest.ok(result)
